#include "videoinput.h"
#include "module_yuvin.h"
#include <QCameraFormat>

VideoInput::VideoInput(QObject *parent) : QObject(parent)
{
    yuvin_module_register();

    m_camera = new QCamera(QMediaDevices::defaultVideoInput());
    m_captureSession.setCamera(m_camera);

    m_captureSession.setVideoSink(&m_videoSink);
    QObject::connect(&m_videoSink, &QVideoSink::videoFrameChanged, this, &VideoInput::on_frame_changed);

    m_camera->start();
}

void VideoInput::on_frame_changed(const QVideoFrame &frame)
{
    QVideoFrame videoFrame = frame;
    /**
     * 我的电脑上返回的格式是Format_NV12：18，每个像素1.5字节，一帧1382400字节，
     * 如果你需要用别的YUV或者RGB格式，则需要自己设置QVideoSink或者QCamera格式
     */
//    QVideoFrameFormat::PixelFormat pixelFormat = videoFrame.pixelFormat();
//    int width = videoFrame.width();
//    int height = videoFrame.height();
    int planeCount = videoFrame.planeCount();
    uchar *pdata = nullptr;
    int len = 0, totallen = 0;

    videoFrame.map(QVideoFrame::ReadOnly);

    for (int i = 0; i < planeCount; i++) {
        pdata = videoFrame.bits(i);
        len = videoFrame.mappedBytes(i);
        if (!yuvmdatalen) // 如果获取到锁
            yuvin_module_putdata((char *)pdata, (int)len, i);
        totallen += len;
    }

//    qDebug("%d, %d, %d, %d, %p, %d",
//           pixelFormat, width, height, planeCount, pdata, totallen);

    videoFrame.unmap();
}

VideoInput::~VideoInput()
{
    m_camera->stop();
}
